<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-设备`"
		width="1200px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		append-to-body
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" :show-message="false" label-width="120px">
			<el-row ref="box1" class="flex-start-center-wrap">
				<el-col :span="8">
					<el-form-item label="编码：" prop="code" class="margin-bottom-10">
						<jk-input v-model="ruleForm.code" placeholder="编码" @change="onCodeChange" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="名称：" prop="name" class="margin-bottom-10">
						<jk-input v-model="ruleForm.name" placeholder="名称" />
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="后道机台编号：" class="margin-bottom-10">
						<jk-input v-model="ruleForm.ltMachineCode" placeholder="名称" />
						<!--<jk-select v-model="ruleForm.ltMachineId" size="medium" class="width-100-percent" :option-list="ltMachineList"></jk-select>-->
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="设备类别：" class="margin-bottom-10">
						<el-select v-model="ruleForm.typeId" clearable placeholder="设备类别" class="width-100-percent" @change="onMachineTypeChange">
							<el-option
								v-for="item in machineTypeList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="工序：" prop="processId" class="margin-bottom-10">
						<el-select v-model="ruleForm.processId" clearable placeholder="工序" class="width-100-percent" @change="onProcessChange">
							<el-option
								v-for="item in processList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="设备机型：" class="margin-bottom-10">
						<el-select v-model="ruleForm.machineModelId" clearable placeholder="设备机型" class="width-100-percent">
							<el-option
								v-for="item in machineModelList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="锭数：" class="margin-bottom-10">
						<jk-number-input v-model="ruleForm.spinCount" class="width-100-percent"></jk-number-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="单价：" class="margin-bottom-10">
						<jk-number-input v-model="ruleForm.unitPrice" class="width-100-percent"></jk-number-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="所属区域：" prop="workshopId" class="margin-bottom-10">
						<el-select v-model="ruleForm.workshopId" clearable placeholder="所属区域" class="width-100-percent">
							<el-option
								v-for="item in workshopList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-tabs v-model="activeTab" type="border-card">
				<el-tab-pane label="基本信息">
					<el-row class="flex-start-center-wrap">
						<el-col :span="8">
							<el-form-item label="生产厂商：" prop="manufacturer" class="margin-bottom-10">
								<jk-input v-model="ruleForm.manufacturer" placeholder="生产厂商" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="出厂编号：" class="margin-bottom-10">
								<jk-input v-model="ruleForm.productionCode" placeholder="出厂编号" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="出厂日期：" class="margin-bottom-10">
								<el-date-picker
									v-model="ruleForm.productionDate"
									type="date"
									style="width: 100%;"
									placeholder="出厂日期"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="是否单锭：" prop="ifSpinOutput" class="margin-bottom-10">
								<el-radio-group v-model="ruleForm.ifSpinOutput">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="是否排产：" prop="ifScheduling" class="margin-bottom-10">
								<el-radio-group v-model="ruleForm.ifScheduling">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="是否样机：" class="margin-bottom-10">
								<el-radio-group v-model="ruleForm.ifTest">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="是否监控：" prop="ifMonitoring" class="margin-bottom-10">
								<el-radio-group v-model="ruleForm.ifMonitoring">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="表数单位：" class="margin-bottom-10">
								<el-radio-group v-model="ruleForm.useMachineOutputKg">
									<el-radio :label="true">公斤</el-radio>
									<el-radio :label="false">米</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="是否换行：" class="margin-bottom-10">
								<el-radio-group v-model="ruleForm.ifLineBreak">
									<el-radio :label="true">是</el-radio>
									<el-radio :label="false">否</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="系数：" class="margin-bottom-10">
								<jk-number-input v-model="ruleForm.outputRatio" class="width-100-percent"></jk-number-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="管重：" class="margin-bottom-10">
								<jk-number-input v-model="ruleForm.pipeQty" class="width-100-percent"></jk-number-input>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="排序：" class="margin-bottom-10">
								<jk-number-input v-model="ruleForm.sortNum" class="width-100-percent"></jk-number-input>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="备注：" prop="remark" class="margin-bottom-10">
								<el-input
									v-model="ruleForm.remark"
									type="textarea"
									:rows="1"
									placeholder="备注"
								/>
							</el-form-item>
						</el-col>
					</el-row>
				</el-tab-pane>
				<el-tab-pane label="锭组">
					<jk-table border :data="ruleForm.spinGroupList" :height="dialogTableHeight - 80">
						<vxe-column title="操作" align="center" field="operation" :width="110">
							<template slot="header">
								<el-button size="mini" type="text" @click="onAddBtn({ rowIndex: ruleForm.spinGroupList ? ruleForm.spinGroupList.length : 0 })">添加</el-button>
							</template>
							<template slot-scope="scope">
								<div class="flex-center">
									<div><el-button size="mini" icon="el-icon-plus" class="item-gap" @click="onAddBtn(scope)"></el-button></div>
									<el-button size="mini" icon="el-icon-minus" @click="onRemoveBtn(scope)"></el-button>
								</div>
							</template>
						</vxe-column>
						<vxe-column title="序号" align="center" type="seq" :width="60" />
						<vxe-column title="开始锭号" align="right" field="startSpinNumber" :min-width="100">
							<template slot-scope="scope">
								<jk-number-input v-model="scope.row.startSpinNumber" size="mini"></jk-number-input>
							</template>
						</vxe-column>
						<vxe-column title="结束锭号" align="right" field="endSpinNumber" :min-width="100">
							<template slot-scope="scope">
								<jk-number-input v-model="scope.row.endSpinNumber" size="mini"></jk-number-input>
							</template>
						</vxe-column>
					</jk-table>
				</el-tab-pane>
				<el-tab-pane label="监控参数">
					<div ref="box3" class="flex-between-center margin-bottom-4">
						<jk-button size="mini" type="primary" icon="el-icon-plus" :disabled="!ruleForm.code" @click="onAddMonitorParamBtn">添加点位</jk-button>
						<div class="flex-start-center">
							<jk-button size="mini" type="primary" class="item-gap" icon="el-icon-document-copy" plain @click="onCopyBtn">复制</jk-button>
							<jk-button size="mini" type="primary" icon="el-icon-document-checked" plain @click="onPasteBtn">粘贴</jk-button>
						</div>
					</div>
					<jk-table ref="jkTable" border :data="ruleForm.monitoringParams" :height="dialogTableHeight - 100">
						<vxe-column width="60" align="center">
							<template #default>
								<div class="drag-btn"><i class="el-icon-rank"></i></div>
							</template>
							<template #header>
								<el-popover title="提示" content="双击拖动调整顺序！" placement="bottom" trigger="hover">
									<i slot="reference" class="el-icon-info drag-info-icon"></i>
								</el-popover>
							</template>
						</vxe-column>
						<vxe-column title="操作" align="center" field="operation" :width="70">
							<template slot-scope="scope">
								<div class="flex-center">
									<el-button size="mini" icon="el-icon-minus" @click="onRemoveTemHumBtn(scope)"></el-button>
								</div>
							</template>
						</vxe-column>
						<vxe-column title="序号" align="center" type="seq" :width="50"></vxe-column>
						<vxe-column title="点位" field="signalName" :min-width="100"></vxe-column>
						<vxe-column title="别名" align="left" field="typeName" :min-width="100">
							<template slot-scope="scope">
								<jk-input v-model="scope.row.typeName" placeholder="" size="mini"></jk-input>
							</template>
						</vxe-column>
						<vxe-column title="纺纱方式" align="left" field="spinTypeId" :width="110">
							<template slot-scope="scope">
								<jk-select v-model="scope.row.spinTypeId" :option-list="spinTypeList" placeholder="" size="mini"></jk-select>
							</template>
						</vxe-column>
						<vxe-column title="单位朝向" align="center" field="unitLocal" :width="110">
							<template slot-scope="scope">
								<el-radio-group v-model="scope.row.unitLocal" size="mini">
									<el-radio-button :label="true">左</el-radio-button>
									<el-radio-button :label="false">右</el-radio-button>
								</el-radio-group>
							</template>
						</vxe-column>
						<vxe-column title="下限值" align="left" field="minValue" :width="100">
							<template slot-scope="scope">
								<jk-input v-model="scope.row.minValue" placeholder="" size="mini"></jk-input>
							</template>
						</vxe-column>
						<vxe-column title="标准值" align="left" field="value" :width="100">
							<template slot-scope="scope">
								<jk-input v-model="scope.row.value" placeholder="" size="mini"></jk-input>
							</template>
						</vxe-column>
						<vxe-column title="上限值" align="left" field="maxValue" :width="100">
							<template slot-scope="scope">
								<jk-input v-model="scope.row.maxValue" placeholder="" size="mini"></jk-input>
							</template>
						</vxe-column>
						<!--<vxe-column title="误差范围" align="left" field="errorRange" :width="100">
                            <template slot-scope="scope">
                                <jk-input v-model="scope.row.errorRange" placeholder="" size="mini"></jk-input>
                            </template>
                        </vxe-column>-->
						<vxe-column title="是否监控" align="center" field="ifMonitoring" :width="70">
							<template slot-scope="scope">
								<el-switch v-model="scope.row.ifMonitoring"></el-switch>
							</template>
						</vxe-column>
						<vxe-column title="是否显示" align="center" field="ifShow" :width="70">
							<template slot-scope="scope">
								<el-switch v-model="scope.row.ifShow"></el-switch>
							</template>
						</vxe-column>
					</jk-table>
				</el-tab-pane>
			</el-tabs>
		</el-form>
		<checkboxSignalDialog
			:machine-code="ruleForm.code"
			:default-select-rows="ruleForm.monitoringParams || []"
			:dialog-state="checkboxSignalDialogState"
			@on-visible-change="onVisibleChangeOfCheckboxSignalDialog"
			@on-confirm="onConfirmOfCheckboxSignalDialog"
		></checkboxSignalDialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        machinemanagerMachineCreate,
        machinemanagerMachineUpdate,
        machinemanagerMachineGet,
        machinemanagerMachinePage, productionIotMachineGetAllSingle
    } from '../../../../api/machine/machineArchives';
    import { systemBusinessDictPage } from '../../../../api/basicData/businessDict';
    import { spinMachineModelPage } from '../../../../api/basicData/machineModel';
    import Sortable from 'sortablejs';
    import checkboxSignalDialog from './checkbox-signal.dialog';
    export default {
        name: 'MachineArchives',
        components: {
            checkboxSignalDialog
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                checkboxSignalDialogState: false,
                ltMachineList: [],
                typeList: [],
                activeTab: '0',
                workshopList: [],
                machineTypeList: [],
                machineModelList: [],
                processList: [],
                saveBtnLoading: false,
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    'useMachineOutputKg': false,
                    'unitPrice': 0,
                    'ifScheduling': true,
                    'ltMachineId': null,
                    'ltMachineCode': null,
                    'ltMachineName': null,
                    'autoGather': true,
                    'ifMonitoring': false,
                    'ifLineBreak': false,
                    'monitoringParams': [],
                    'spinGroupList': [],
                    'code': '',
                    'spinCount': null,
                    'factoryCode': '',
                    'installDate': '',
                    'intoProductionDate': '',
                    'ip': '',
                    'ifSpinOutput': false,
                    'isScheduling': true,
                    'isSpinOutput': true,
                    'machineModelCode': '',
                    'machineModelId': null,
                    'machineModelName': '',
                    'manufacturer': '',
                    'maxOutputQty': 0,
                    'auditState': 1,
                    'name': '',
                    'pipeQty': null,
                    'outputRatio': 0,
                    'processCode': '',
                    'processId': null,
                    'processName': '',
                    'prodTime': '',
                    'spinUsed': 0,
                    'typeCode': '',
                    'typeId': null,
                    'typeName': '',
                    'workshopId': null,
                    'workshopName': ''
                },
                rules: {
                    typeId: [{ required: true, trigger: 'change' }],
                    code: [{ required: true, trigger: 'change' }],
                    workshopId: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }],
                    processId: [{ required: true, trigger: 'change' }]
                },
                defaultRowData: {
                    startSpinNumber: null,
                    endSpinNumber: null
                },
                spinTypeList: []
            };
        },
        methods: {
            onConfirmOfCheckboxSignalDialog(arr) {
                arr.forEach(item => {
                    this.ruleForm.monitoringParams.push({
                        typeId: item.typeId,
                        signalId: item.id,
                        signalCode: item.code,
                        signalName: item.name,
                        typeName: item.name, // 注：typeName: 已被用作signalName的别名
                        errorRange: null,
                        maxValue: null,
                        minValue: null,
                        ifMonitoring: true,
                        ifShow: true,
                        value: null,
                        unitLocal: true
                    });
                });
                this.checkboxSignalDialogState = false;
            },
            onVisibleChangeOfCheckboxSignalDialog(e) {
                this.checkboxSignalDialogState = e;
            },
            loadSortTable() {
                this.$nextTick(() => {
                    const xTable = this.$refs.jkTable.$refs.xTable;
                    this.sortable1 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
                        handle: '.drag-btn',
                        animation: 500,
                        onEnd: ({ newIndex, oldIndex }) => {
                            const currRow = this.ruleForm.monitoringParams.splice(oldIndex, 1)[0];
                            this.ruleForm.monitoringParams.splice(newIndex, 0, currRow);
                        }
                    });
                });
            },
            onCodeChange() {
                this.getMonitorTypeListRequest();
            },
            onCopyBtn() {
                localStorage.setItem('signalList', JSON.stringify(this.ruleForm.monitoringParams));
            },
            onPasteBtn() {
                const arr = localStorage.getItem('signalList') ? JSON.parse(localStorage.getItem('signalList')) : [];
                arr.forEach(x => {
                    delete x.id;
                });
                this.$set(this.ruleForm, 'monitoringParams', arr);
            },
            onAddMonitorParamBtn() {
                this.checkboxSignalDialogState = true;
            },
            onRemoveTemHumBtn(scope) {
                this.ruleForm.monitoringParams.splice(scope.rowIndex, 1);
            },
            onAddBtn(scope) {
                this.ruleForm.spinGroupList.splice(scope.rowIndex + 1, 0, JSON.parse(JSON.stringify(this.defaultRowData)));
            },
            onRemoveBtn(scope) {
                this.ruleForm.spinGroupList.splice(scope.rowIndex, 1);
            },
            onMachineTypeChange(e) {
                this.machineModelList = [];
                this.$set(this.ruleForm, 'machineModelId', null);
                this.$set(this.ruleForm, 'machineModelCode', '');
                this.$set(this.ruleForm, 'machineModelName', '');
                this.getMachineModelListRequest();
            },
            onProcessChange() {
                this.machineModelList = [];
                this.$set(this.ruleForm, 'machineModelId', null);
                this.$set(this.ruleForm, 'machineModelCode', '');
                this.$set(this.ruleForm, 'machineModelName', '');
                this.getMachineModelListRequest();
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                const processItem = this.processList.find(x => x.id === params.processId) || {};
                params.processName = processItem.name;
                params.processCode = processItem.code;

                const machineModelItem = this.machineModelList.find(x => x.id === params.machineModelId) || {};
                params.machineModelName = machineModelItem.name;
                params.machineModelCode = machineModelItem.code;

                const workshopItem = this.workshopList.find(x => x.id === params.workshopId) || {};
                params.workshopName = workshopItem.name;
                params.workshopCode = workshopItem.code;

                const typeItem = this.machineTypeList.find(x => x.id === params.typeId) || {};
                params.typeName = typeItem.name;
                params.typeCode = typeItem.code;

                params.spinGroupList = params.spinGroupList ? params.spinGroupList.map((x, idx) => {
                    x.sortNum = idx;
                    return x;
                }) : [];

                let spinTypeItem = {};

                params.monitoringParams = params.monitoringParams ? params.monitoringParams.map((x, index) => {
                    x.sortNum = index + 1;
                    spinTypeItem = this.spinTypeList.find(k => k.id === x.spinTypeId) || {};
                    x.spinTypeCode = spinTypeItem.code;
                    x.spinTypeName = spinTypeItem.name;
                    return x;
                }) : [];

                const ltItem = this.ltMachineList.find(x => x.code === params.ltMachineCode) || {};
                params.ltMachineId = ltItem.id;
                params.ltMachineName = ltItem.name;
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const api = !this.dataId ? machinemanagerMachineCreate : machinemanagerMachineUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return machinemanagerMachineGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                    }
                });
            },
            getTypeListRequest() {
                return systemBusinessDictPage({ categoryCode: 'MACHINE_TYPE' }).then(res => {
                    if (res.data.status === 200) {
                        this.machineTypeList = res.data.res;
                    }
                });
            },
            getMachineModelListRequest() {
                if (!this.ruleForm.typeId) return;
                return spinMachineModelPage({
                    processId: this.ruleForm.processId,
                    typeId: this.ruleForm.typeId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.machineModelList = res.data.res || [];
                    }
                });
            },
            getMonitorTypeListRequest() {
                this.typeList = [];
                if (!this.ruleForm.code) return;
                return productionIotMachineGetAllSingle({
                    number: this.ruleForm.code
                }).then(res => {
                    if (res.data.status === 200) {
                        this.typeList = res.data.res ? res.data.res.map(x => {
                            return x;
                        }) : [];
                    }
                });
            },
            getMachineListRequest() {
                return machinemanagerMachinePage({
                    auditState: 1,
                    pageNo: 1,
                    pageSize: 1000
                }).then(res => {
                    if (res.data.status === 200) {
                        this.ltMachineList = res.data.res || [];
                    }
                });
            },
            getSpinTypeListRequest() {
                return systemBusinessDictPage({ categoryCode: 'SPIN_TYPE' }).then(res => {
                    if (res.data.status === 200) {
                        this.spinTypeList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                }
                this.processList = this.$store.state.user.userProcess.processList;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                await this.getMachineListRequest();
                await this.getSpinTypeListRequest();
                await this.getTypeListRequest();
                if (this.dataId) await this.getDetailRequest();
                await this.getMonitorTypeListRequest();
                if (this.ruleForm.typeId) await this.getMachineModelListRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.loadSortTable();
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
.drag-info-icon {
    font-size: 14px;
}
.drag-btn {
    cursor: move;
    color: #2d8cf0;
    transition: all .5s;
    font-size: 18px;
}
.drag-btn:hover {
    //transform: rotate(90deg);
}
</style>
